from decimal import Decimal

from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from goods.models import SKU
from order.models import OrderInfo
from order.serializers import PlaceOrderSerializer, PlaceSerializer, OrderListSerializer, OrderListSKUSerializer, \
    CommentOrderSerializer


class PlaceOrderAPIView(APIView):
    """
    订单处理
    前端必须传递一个用户信息 token

    1. 这个视图必须是登陆用户才可以访问
    2. 获取用户信息
    3. 根据用户信息获取redis中选中的商品id  [1,2,3,4,5]
    4. 根据id查询商品信息  [sku,sku,sku]
    5. 将对象列表转换为字典列表
    6. 返回相应

    """

    # 1. 这个视图必须是登陆用户才可以访问
    permission_classes = [IsAuthenticated]
    def get(self,request):
        # 2. 获取用户信息
        user = request.user
        # 3. 根据用户信息获取redis中选中的商品id  [1,2,3,4,5]
        redis_conn = get_redis_connection('cart')
        sku_id_counts = redis_conn.hgetall('cart_%s'%user.id)
        # 将我们的数据有bytes类型转换为 int类型
        redis_cart = {}
        for sku_id,count in sku_id_counts.items():
            redis_cart[int(sku_id)]=int(count)

        # sku_id_counts = {b'':b''}
        selected_ids = redis_conn.smembers('cart_selected_%s'%user.id)
        # [id,id,id]

        # 4. 根据id查询商品信息  [sku,sku,sku]
        skus = SKU.objects.filter(pk__in=selected_ids)

        for sku in skus:
            sku.count = redis_cart[sku.id]

        # 5. 将对象列表转换为字典列表
        # serializer = PlaceOrderSerializer(skus,many=True)

        #价格,最好使用 货币类型
        # from decimal import Decimal
        # # decimal 可以保存数据存储的精度
        # #  我们的小数在计算机中是以 无限接近于真实值的形式存在的
        #
        # # 100元 分3期  100/3=33.33     33.33+33.33+33.33=99.99
        # # 100元 分3期  100/3=33.33     33.33+33.33+33.34=100
        #
        # # 100万
        #
        # freight = Decimal('10')
        # result = {
        #     'freight':freight,
        #     'skus':serializer.data
        # }

        # 6. 返回相应
        # return Response(result)



        freight = Decimal('10')
        serializer = PlaceSerializer({
            'skus':skus,
            'freight':freight

        })
        return Response(serializer.data)


from .serializers import OrderSerializer

class OrderAPIView(APIView):
    # 订单的提交和展示
    permission_classes = [IsAuthenticated]

    def post(self,request):
        # 1,接收数据
        data = request.data
        # 2.验证数据
        serializer = OrderSerializer(data=data,context={'request':request})
        # 3.数据入库
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 4.返回相应
        return Response(serializer.data)





    #新增
    def get(self, request):
        """
        订单列表展示
        """
        # 接收参数
        page = request.query_params.get('page')
        page_size = request.query_params.get('page_size')

        # 获取对应用户的订单
        orders = OrderInfo.objects.filter(user=request.user).order_by('-create_time')
        count = orders.count()
        orders_page = Paginator(orders, page_size).page(page)

        skus = []
        for order in orders_page:
            # 修改订单状态
            if order.skus.filter(is_commented=False).count() == 0:
                order.status = OrderInfo.ORDER_STATUS_ENUM['FINISHED']
                order.save()

            skus.append(order.skus)

        # 创建序列化器
        serializer = OrderListSerializer(instance=orders_page, many=True, context={'skus': skus})
        # 返回响应
        data = {
            'count': count,
            'results': serializer.data
        }
        return Response(data)



class CommentOrderAPIView(APIView):
    """
    订单评价
    """
    # 只有登录用户才有权限访问
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        """
        订单评论页面展示
        """
        if not order_id:
            return Response({'message': '请求参数错误'})
        # 根据 订单id 查询商品
        skus = OrderInfo.objects.get(pk=order_id, user=request.user).skus.filter(is_commented=False)
        # 创建序列化器
        serializer = OrderListSKUSerializer(instance=skus, many=True)
        # 返回响应
        return Response(serializer.data)


class CommentOrderSKUAPIView(APIView):
    """
    订单商品评价
    """
    # 只有登录用户才有权限访问
    permission_classes = [IsAuthenticated]

    def post(self, request, order_id):
        """
        订单评论提交
        """
        if not order_id:
            return Response({'message': '请求参数错误'})

        # 接收数据 is_annoymous, score, comment, order_id, sku_id
        data = request.data
        order_id = request.data.get('order')
        # 查询订单商品
        order = OrderInfo.objects.get(pk=order_id, user=request.user)
        # 根据订单查询商品
        sku_id = request.data.get('sku')
        ordergood = order.skus.get(is_commented=False, sku_id=sku_id)
        # 创建序列化器校验数据
        serializer = CommentOrderSerializer(instance=ordergood, data= data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        # 保存数据 抛出异常: AttributeError: 'QuerySet' object has no attribute '_meta', 需要使用get获取查询集,而不是filter
        serializer.save()

        # 返回响应
        return Response(serializer.data)